/**
 * 格式化工具函数
 */

/**
 * 格式化数字
 * @param {number} num - 数字
 * @param {Object} options - 选项
 * @returns {string} 格式化后的数字
 */
export function formatNumber(num, options = {}) {
  if (typeof num !== 'number' || isNaN(num)) {
    return '0';
  }

  const {
    decimals = 2,
    thousandsSeparator = ',',
    decimalSeparator = '.',
    prefix = '',
    suffix = '',
  } = options;

  const fixed = num.toFixed(decimals);
  const parts = fixed.split('.');
  const integerPart = parts[0].replace(
    /\B(?=(\d{3})+(?!\d))/g,
    thousandsSeparator
  );
  const decimalPart = parts[1] ? decimalSeparator + parts[1] : '';

  return prefix + integerPart + decimalPart + suffix;
}

/**
 * 格式化货币
 * @param {number} amount - 金额
 * @param {string} currency - 货币符号
 * @param {Object} options - 选项
 * @returns {string} 格式化后的货币
 */
export function formatCurrency(amount, currency = '¥', options = {}) {
  const {
    decimals = 2,
    thousandsSeparator = ',',
    decimalSeparator = '.',
    symbolPosition = 'before',
  } = options;

  const formatted = formatNumber(amount, {
    decimals,
    thousandsSeparator,
    decimalSeparator,
  });

  return symbolPosition === 'before'
    ? currency + formatted
    : formatted + currency;
}

/**
 * 格式化文件大小
 * @param {number} bytes - 字节数
 * @param {number} decimals - 小数位数
 * @returns {string} 格式化后的文件大小
 */
export function formatFileSize(bytes, decimals = 2) {
  if (bytes === 0) {
    return '0 Bytes';
  }

  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

/**
 * 格式化百分比
 * @param {number} value - 值
 * @param {number} total - 总数
 * @param {number} decimals - 小数位数
 * @returns {string} 格式化后的百分比
 */
export function formatPercentage(value, total, decimals = 2) {
  if (total === 0) {
    return '0%';
  }
  const percentage = (value / total) * 100;
  return percentage.toFixed(decimals) + '%';
}

/**
 * 格式化手机号
 * @param {string} phone - 手机号
 * @param {string} separator - 分隔符
 * @returns {string} 格式化后的手机号
 */
export function formatPhone(phone, separator = ' ') {
  if (!phone || typeof phone !== 'string') {
    return '';
  }

  const cleaned = phone.replace(/\D/g, '');
  if (cleaned.length !== 11) {
    return phone;
  }

  return cleaned.replace(
    /(\d{3})(\d{4})(\d{4})/,
    `$1${separator}$2${separator}$3`
  );
}

/**
 * 格式化身份证号
 * @param {string} idCard - 身份证号
 * @param {string} separator - 分隔符
 * @returns {string} 格式化后的身份证号
 */
export function formatIdCard(idCard, separator = ' ') {
  if (!idCard || typeof idCard !== 'string') {
    return '';
  }

  const cleaned = idCard.replace(/\D/g, '');
  if (cleaned.length === 15) {
    return cleaned.replace(
      /(\d{6})(\d{6})(\d{3})/,
      `$1${separator}$2${separator}$3`
    );
  } else if (cleaned.length === 18) {
    return cleaned.replace(
      /(\d{6})(\d{8})(\d{4})/,
      `$1${separator}$2${separator}$3`
    );
  }

  return idCard;
}

/**
 * 格式化银行卡号
 * @param {string} cardNumber - 银行卡号
 * @param {string} separator - 分隔符
 * @returns {string} 格式化后的银行卡号
 */
export function formatBankCard(cardNumber, separator = ' ') {
  if (!cardNumber || typeof cardNumber !== 'string') {
    return '';
  }

  const cleaned = cardNumber.replace(/\D/g, '');
  return cleaned.replace(/(\d{4})(?=\d)/g, `$1${separator}`);
}

/**
 * 格式化时间戳
 * @param {number} timestamp - 时间戳
 * @param {string} format - 格式
 * @returns {string} 格式化后的时间
 */
export function formatTimestamp(timestamp, format = 'YYYY-MM-DD HH:mm:ss') {
  if (!timestamp) {
    return '';
  }

  const date = new Date(timestamp);
  if (isNaN(date.getTime())) {
    return '';
  }

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds);
}

/**
 * 格式化JSON
 * @param {any} data - 数据
 * @param {number} space - 缩进空格数
 * @returns {string} 格式化后的JSON
 */
export function formatJSON(data, space = 2) {
  try {
    return JSON.stringify(data, null, space);
  } catch (error) {
    return String(data);
  }
}

/**
 * 格式化HTML
 * @param {string} html - HTML字符串
 * @returns {string} 格式化后的HTML
 */
export function formatHTML(html) {
  if (!html || typeof html !== 'string') {
    return '';
  }

  const div = document.createElement('div');
  div.innerHTML = html.trim();

  return div.innerHTML;
}

/**
 * 格式化URL参数
 * @param {Object} params - 参数对象
 * @returns {string} URL参数字符串
 */
export function formatUrlParams(params) {
  if (!params || typeof params !== 'object') {
    return '';
  }

  const searchParams = new URLSearchParams();

  for (const key in params) {
    if (
      Object.prototype.hasOwnProperty.call(params, key) &&
      params[key] !== null &&
      params[key] !== undefined
    ) {
      searchParams.append(key, params[key]);
    }
  }

  return searchParams.toString();
}

/**
 * 解析URL参数
 * @param {string} url - URL字符串
 * @returns {Object} 参数对象
 */
export function parseUrlParams(url) {
  if (!url || typeof url !== 'string') {
    return {};
  }

  try {
    const urlObj = new URL(url);
    const params = {};

    for (const [key, value] of urlObj.searchParams) {
      params[key] = value;
    }

    return params;
  } catch (error) {
    return {};
  }
}
